<?php
/**
 * Created by PhpStorm.
 * Author: lbf
 * Date: 2018/5/16
 * Time: 18:55
 * Desc: 钉钉通知
 */

namespace Library\DingTalk;

class Action
{
    ##资产不够报警,交易监控,bz告警
    static protected $hooks = [
        'distribute' => '12312312312312'
    ];

    const TEMPLATE_MSG = [
        'distribute' => <<<STR
# 分发结果
%s
STR
        ,
    ];

    /**
     * @desc markDown 格式
     * @author lbf
     * @param $markDown
     * @param string $type
     * @param string $title
     * @param bool $isAtAll
     * @return bool|mixed
     *------------------------------------------------------
     */
    public static function sendMarkDown($markDown, $type, $title, $isAtAll = false)
    {
        $message = array('msgtype' => 'markdown', 'markdown' => array('title' => $title, 'text' => $markDown), 'at' => array('isAtAll' => $isAtAll));
        $data_string = json_encode($message);

        return self::request_by_curl(self::$hooks[$type], $data_string);
    }

    /**
     * @desc 发送消息
     * @author lbf
     * @param $remote_server
     * @param $post_string
     * @return mixed
     *------------------------------------------------------
     */
    public static function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    /**
     * @desc 发送钉钉文本消息
     * @author lbf
     * @param $message
     * @param string $type
     * @param bool $isAtAll
     * @return bool|mixed
     *------------------------------------------------------
     */
    public static function sendMsg($message, $type = 'assets', $isAtAll = false)
    {
        if (!isset(self::$hooks[$type]) || !self::$hooks[$type]) {
            return false;
        }

        $data = array('msgtype' => 'text', 'text' => array('content' => $message), 'at' => array('isAtAll' => $isAtAll));

        $data_string = json_encode($data);

        return self::request_by_curl(self::$hooks[$type], $data_string);
    }

}